<template>
    <div class="file-distribution-container">
        <div class="header">
            <div class="header-left">
                <router-link :to="listPath" class="back-btn">
                    <i class="el-icon-arrow-left"></i> 返回
                </router-link>
                
                <div class="save-info">
                    <el-button type="success" icon="el-icon-check" @click="saveRecord" v-if="!isView">保存</el-button>
                    <el-button type="info" icon="el-icon-printer" @click="printForm">打印</el-button>
                </div>
            </div>
            <h2 style="text-align: center;">文件发放与回收记录</h2>
            <div class="file-info">
                <div @dblclick="editFileNumber = true && !isView">
                    <span v-if="!editFileNumber">文件编号：{{ fileNumber }}</span>
                    <input v-else type="text" v-model="fileNumber" @blur="editFileNumber = false"
                        @keyup.enter="editFileNumber = false" placeholder="请输入文件编号">
                </div>

                <div class="add-department" v-if="!isView">
                    <input type="text" v-model="newDepartment" placeholder="请输入新部门名称">
                    <el-button size="small" type="primary" @click="addDepartment">添加部门</el-button>
                </div>

                <div @dblclick="editFileName = true && !isView">
                    <span v-if="!editFileName">文件名称：{{ fileName }}</span>
                    <input v-else type="text" v-model="fileName" @blur="editFileName = false"
                        @keyup.enter="editFileName = false" placeholder="请输入文件名称">
                </div>
            </div>
            <el-table :data="distributionList" border style="width: 100%">
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="distributionDepartment" label="分发部门" width="120"></el-table-column>
                <el-table-column prop="distributionNumber" label="分发编号" width="100"></el-table-column>
                <el-table-column prop="version" label="版本" width="80"></el-table-column>
                <el-table-column prop="copyNumber" label="份数" width="80"></el-table-column>
                <el-table-column label="接收人" width="120">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.receiver" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="接收日期" width="140">
                    <template slot-scope="scope">
                        <el-date-picker v-model="scope.row.receiveDate" type="date" 
                            value-format="yyyy-MM-dd" :disabled="isView"></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="回收人" width="120">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.collector" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="回收日期" width="140">
                    <template slot-scope="scope">
                        <el-date-picker v-model="scope.row.collectDate" type="date" 
                            value-format="yyyy-MM-dd" :disabled="isView"></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="备注">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remark" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
import { getKaoqinWenjianById, saveKaoqinWenjian } from '@/api/kaoqinWenjian'

export default {
    name: 'FileDistributionRecord',
    data() {
        return {
            listPath: '/main/renshi/kaoqing/wjhuishou/wjhuishouList',
            fileNumber: '',
            fileName: '',
            distributionList: [],
            newDepartment: '',
            editFileNumber: false,
            editFileName: false,
            isView: false
        }
    },
    created() {
        const { id, type } = this.$route.query
        this.isView = type === 'view'
        if (id) {
            this.fetchData(id)
        } else {
            this.initData()
        }
    },
    methods: {
        initData() {
            this.fileNumber = 'WI-A-JY-38'
            this.fileName = '考勤管理办法'
            this.distributionList = [
                {
                    distributionDepartment: '总经理室',
                    distributionNumber: '01',
                    version: 'B/0',
                    copyNumber: 1,
                    receiver: '',
                    receiveDate: '',
                    collector: '',
                    collectDate: '',
                    remark: ''
                },
                {
                    distributionDepartment: '管理者代表',
                    distributionNumber: '02',
                    version: 'B/0',
                    copyNumber: 1,
                    receiver: '',
                    receiveDate: '',
                    collector: '',
                    collectDate: '',
                    remark: ''
                }
            ]
        },
        async fetchData(id) {
            try {
                const { data } = await getKaoqinWenjianById(id)
                if (data.code === 200 && data.data) {
                    this.fileNumber = data.data.fileNumber || ''
                    this.fileName = data.data.fileName || ''
                    if (Array.isArray(data.data.details)) {
                        this.distributionList = data.data.details
                    } else {
                        this.distributionList = []
                        console.warn('Details data is not an array:', data.data.details)
                    }
                } else {
                    this.$message.error(data.message || '获取数据失败')
                }
            } catch (error) {
                console.error('获取数据失败:', error)
                this.$message.error('获取数据失败')
            }
        },
        printForm() {
            window.print()
        },
        addDepartment() {
            if (this.newDepartment.trim() !== '') {
                const newItem = {
                    distributionDepartment: this.newDepartment,
                    distributionNumber: (this.distributionList.length + 1).toString().padStart(2, '0'),
                    version: 'B/0',
                    copyNumber: 1,
                    receiver: '',
                    receiveDate: '',
                    collector: '',
                    collectDate: '',
                    remark: ''
                }
                this.distributionList.push(newItem)
                this.newDepartment = ''
            } else {
                this.$message.warning('请输入部门名称')
            }
        },
        async saveRecord() {
            if (!this.fileNumber.trim()) {
                return this.$message.warning('请输入文件编号')
            }
            if (!this.fileName.trim()) {
                return this.$message.warning('请输入文件名称')
            }
            if (this.distributionList.length === 0) {
                return this.$message.warning('请添加至少一个部门')
            }

            try {
                const data = {
                    id: this.$route.query.id,
                    fileNumber: this.fileNumber,
                    fileName: this.fileName,
                    details: this.distributionList
                }
                await saveKaoqinWenjian(data)
                this.$message.success('保存成功')
                this.$router.push({
                    name: 'WjhuishouList',
                    query: {
                        type: 'list'
                    }
                })
            } catch (error) {
                console.error('保存失败:', error)
                this.$message.error('保存失败')
            }
        }
    }
}
</script>

<style scoped lang="scss">
.file-distribution-container {
    font-family: '宋体', sans-serif;
    padding: 20px;
    height: calc(100vh - 40px);
}

.header {
    width: 1200px;
    margin: 0 auto;
}

.file-info {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
}

.header-left {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    color: #409EFF;

    i {
        // font-size: 20px;
        color: #409EFF;
    }

    a.back-btn.router-link-active {
        color: #409EFF;
    }
}

.add-department {
    // margin-bottom: 15px;
    display: flex;
    gap: 10px;
}

.distribution-table {
    width: 100%;
    border-collapse: collapse;
}

.distribution-table th,
.distribution-table td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: center;
}

.save-info {
    margin-top: 15px;
    display: flex;
    justify-content: end;
    align-items: center;
}

@media print {
    .header {
        // width: 800px;
        margin: 0px;
    }

    .header-left {
        display: none;
    }

    .add-department {
        display: none;
    }

    table {
        margin: 10px 0px;
    }

    .info-table,
    .content-table,
    .approval-table {
        border: 1px solid #000;

        td,
        th {
            border: 1px solid #000;
        }
    }

    td,
    th {
        padding: 5px;
        border: 1px solid #000;
        white-space: nowrap;
    }

    input {
        border: none !important;
        background-color: transparent !important;
        text-align: center;
    }

    textarea {
        border: 0px !important;
    }
}
</style>